package com.ethanzzh.ethanzzh_xdclass.service;

import com.ethanzzh.ethanzzh_xdclass.config.WeChatConfig;
import com.ethanzzh.ethanzzh_xdclass.mapper.UserMapper;
import com.ethanzzh.ethanzzh_xdclass.model.pojo.User;
import com.ethanzzh.ethanzzh_xdclass.utils.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    private WeChatConfig weChatConfig;

    private static final Logger LOGGER = LoggerFactory.getLogger(UserService.class);

    @Autowired
    private UserMapper userMapper;

    public User saveWeChatUser(String code) {

        String accessTokenUrl = String.format(weChatConfig.getOpenAccessTokenUrl(), weChatConfig.getOpenAppId(), weChatConfig.getOpenAppSecret(), code);

        //获取access_token
        Map<String, Object> baseMap = HttpUtils.doGet(accessTokenUrl);
        if (baseMap == null || baseMap.isEmpty()) {
            return null;
        }
        String accessToken = (String) baseMap.get("access_token");
        String openId = (String) baseMap.get("openid");

        //获取用户基本信息
        String userInfoUrl = String.format(WeChatConfig.getOpenUserInfoUrl(), accessToken, openId);

        User dbUser = userMapper.findByOpenId(openId);
        if (dbUser != null) {
            return dbUser;
        }

        Map<String, Object> baseUserMap = HttpUtils.doGet(userInfoUrl);
        if (baseUserMap == null || baseUserMap.isEmpty()) {
            return null;
        }
        String nickname = (String) baseUserMap.get("nickname");
        Double sexTemp = (Double) baseUserMap.get("sex");
        int sex = sexTemp.intValue();
        String province = (String) baseUserMap.get("province");
        String city = (String) baseUserMap.get("city");
        String country = (String) baseUserMap.get("country");
        String headimgurl = (String) baseUserMap.get("headimgurl");

        //多字符串拼接
        StringBuilder sb = new StringBuilder(country).append("||").append(province).append("||").append(city);
        String finalAddress = sb.toString();

        try {
            //解决乱码
            nickname = new String(nickname.getBytes("ISO-8859-1"), "UTF-8");
            finalAddress = new String(finalAddress.getBytes("ISO-8859-1"), "UTF-8");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        User user = new User();
        user.setName(nickname);
        user.setHeadImg(headimgurl);
        user.setCity(finalAddress);
        user.setOpenid(openId);
        user.setSex(sex);
        user.setCreateTime(new Date());


        userMapper.insertSelective(user);

        return user;

    }

    @Cacheable(value = "user", key = "#id", sync = true)
    public User getUser(Integer id) {
        User user = userMapper.getUser(id);
        LOGGER.info("[spring 缓存]user : {}做了缓存",id);
        return user;
    }

}
